package qingxin.servlet.admin.journalist;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import qingxin.dao.JournalistDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.Journalist;

@WebServlet("/admin/journalist/add")
public class AddJournalistServlet extends AdminServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JournalistDAO journalistDAO;

	public AddJournalistServlet(){
		super();
		journalistDAO = DAOFactory.getJournalistDAO();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			String journalistS = request.getParameter("journalist");
			JSONObject jsonJournalist = new JSONObject(journalistS);
			
			Journalist journalist = new Journalist();
			journalist.setAvatarID(jsonJournalist.getInt("avatar"));
			journalist.setBirthday(jsonJournalist.getString("birthday"));
			journalist.setClassName(jsonJournalist.getString("class"));
			journalist.setConstellation(jsonJournalist.getString("constellation"));
			journalist.setIntroduction(jsonJournalist.getString("introduction"));
			journalist.setMotto(jsonJournalist.getString("motto"));
			journalist.setName(jsonJournalist.getString("name"));
			journalist.setSex(jsonJournalist.getString("sex"));
			journalist.setRetired(jsonJournalist.getBoolean("isRetired"));
			
			journalistDAO.add(journalist);
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
			
}
